package com.lyh.hkcloud.module.common;

/**
 * @author: zhongfan
 * @program: hkCloud
 * @description:
 * @company—date: 利元数据 2022-03-31 14:22
 **/

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.lyh.hkcloud.R;
import com.lyh.hkcloud.util.AppUtils;
import org.json.JSONObject;

public class UpdateManager {

    private Context mContext;

    private boolean intercept = false;

    private String apkUrl;

    /**
     * 保存APK的文件夹
     */
    private static final String savePath = "/sdcard/updatedemo/";
    private static final String saveFileName = savePath + "app-release.apk";

    /**
     * 下载线程
     */
    private Thread downLoadThread;

    /**
     * 当前进度
      */
    private int progress;

    /**
     * 进度条与通知UI刷新的handler和msg常量
     */
    private ProgressBar mProgress;
    private TextView tvNumber;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;

    JSONObject object;

    public UpdateManager(Context context, JSONObject object) {
        apkUrl = object.optString("filePath");
        this.object = object;
        mContext = context;
    }

    /**
     * 检查是否更新的内容
     */
    public void checkUpdateInfo() {
        long versionCode1 = AppUtils.getVersionCode(mContext);
        //Double versionCode = Double.parseDouble(object.optString("major"));

        /*if (true) {
            showDownloadDialog();
            return;
        }*/
        if (Double.parseDouble(object.optString("major")) > versionCode1) {
           showUpdateDialog();
        }
    }

    /**
     * 显示更新程序对话框，供主程序调用
     */
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("系统更新");
        builder.setCancelable(false);
        builder.setMessage(object.optString("content"));
        builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.create().show();
    }

    /**
     * 显示下载进度的对话框
     */
    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(false);
        builder.setTitle("下载最新系统");
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.activity_progress_bar, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);
        tvNumber = v.findViewById(R.id.tv_number);

        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                intercept = true;
            }
        });
        builder.show();
        downloadApk();
    }

    /**
     * 从服务器下载APK安装包
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private Runnable mdownApkRunnable = new Runnable() {

        @Override
        public void run() {
            URL url;
            try {
                url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                if (conn.getResponseCode() != 200) {
                    Toast.makeText(mContext, "下载失败！", Toast.LENGTH_SHORT).show();
                    return;
                }
                conn.connect();
                int length = conn.getContentLength();conn.getContent();
                InputStream ins = conn.getInputStream();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                File apkFile = new File(saveFileName);
                FileOutputStream fos = new FileOutputStream(apkFile);
                int count = 0;/*apkFile.length();ins.read();file.length();*/
                byte[] buf = new byte[1024];
                while (!intercept) {
                    int numread = ins.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 下载进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                }
                fos.close();
                ins.close();

            } catch (Exception e) {
                Toast.makeText(mContext, "下载失败！", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    };

    /**
     * 安装APK内容
     */
    private void installAPK() {
        File apkFile = new File(saveFileName);
        if (!apkFile.exists()) {
            return;
        }

//        if (!getFileMd5(apkFile).equals(object.optString("md5"))) {
//            Toast.makeText(mContext, "md5检测失败", Toast.LENGTH_SHORT).show();
//            return;
//        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {

                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    tvNumber.setText(String.valueOf(progress));
                    break;
                case DOWN_OVER:
                    installAPK();
                    break;

                default:
                    break;
            }
        }

    };

    /**
     * MD5校验
     *
     * @param targetFile    要校验md5的文件
     * @return              文件的md5
     */
    public static String getFileMd5(File targetFile) {

        if (targetFile == null || !targetFile.isFile()){
            return null;
        }

        MessageDigest digest;
        FileInputStream fis = null;
        byte[] buffer = new byte[1024];
        try {
            digest = MessageDigest.getInstance("MD5");
            fis = new FileInputStream(targetFile);
            int bufferLen;
            while ((bufferLen = fis.read(buffer)) != -1){
                digest.update(buffer,0,bufferLen);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        byte[] result = digest.digest();
        BigInteger bigInteger = new BigInteger(1,result);

        return bigInteger.toString(16);
    }

}

